<template>
	<view
		class="layout"
		:class="{
			skelett: isSkelett,
			footer: !!downFileLength || isDisabled
		}"
	>
		<view class="layout-nav">
			<DistributionNavBar title="详情" :rgb="navBarRgba">
				<template slot="left">
					<image :src="bankIcon" @click="clickBack" />
				</template>
			</DistributionNavBar>
		</view>

		<view class="layout-header">
			<CommonMateriaHeader title="商品及订单信息" :titleIcon="headerIcon" :height="100" :isSkelett="isSkelett" isBgColor>
				<view class="layout-header-main">
					<view class="layout-header-main-product">
						<DistributionMaterial isPreview :skelettSize="1" :isSkelett="isSkelett" :isFooter="false" :list="materailList" />
					</view>

					<view class="layout-header-main-type">
						<view class="layout-header-main-type-item" :key="item.type" v-for="item in materialBuyTypeList">
							<view class="layout-header-main-type-item-left">
								<text>{{ item.label }}</text>
							</view>

							<view class="layout-header-main-type-item-right">
								<template v-if="!isSkelett">
									{{ item.prefix || '' }}
								</template>
								<text :class="{ realPayment: item.prefix }">¥{{ pageParams[item.type] }}</text>
							</view>
						</view>
					</view>

					<view class="layout-header-main-order">
						<view class="layout-header-main-order-item" :key="item.type" v-for="item in orderTypeList">
							<view class="layout-header-main-order-item-left">
								<text>{{ item.label }}</text>
							</view>

							<view class="layout-header-main-order-item-right">
								<text>{{ pageParams[item.type] }}</text>

								<template v-if="item.copy">
									<button @click.stop.prevent="copyOrderNo(item)">复制</button>
								</template>
							</view>
						</view>
					</view>
				</view>
			</CommonMateriaHeader>
		</view>

		<view class="layout-main">
			<view class="layout-main-tabs">
				<view class="layout-main-tabs-left">
					<DistributionSubTabs
						height="100rpx"
						v-model="tabsType"
						:list="tabsTypeList"
						:isSkelett="isSkelett"
						@beforeCallBack="changeTypeTabs"
					/>
				</view>
				<view class="layout-main-tabs-right">
					<template v-if="!isSkelett">
						<button @click.prevent.stop="changeBatchDownloadStatus">{{ batchDownStatus ? '批量下载' : '取消' }}</button>
					</template>
				</view>
			</view>

			<view class="layout-main-content">
				<swiper class="swiper" :current-item-id="tabsType" skip-hidden-item-layout @change="changeTabsType" :style="[swiperStyle]">
					<swiper-item itemId="image">
						<view class="layout-main-content-item">
							<MaterialDownloadResource
								:skelettSize="4"
								:isPreview="false"
								:disabled="isDisabled"
								:isSkelett="isSkelett"
								:otherParams="{
									type: 'image'
								}"
								:batchDownLoad="!batchDownStatus"
								:singleDownLoad="batchDownStatus"
								:list="materialFileObject.imageList"
								@openPreview="openPreview"
								@singleFileDownload="singleFileDownload"
								@changeResourceListStatus="changeResourceListStatus"
							/>
						</view>
					</swiper-item>

					<swiper-item itemId="video">
						<view class="layout-main-content-item">
							<MaterialDownloadResource
								:skelettSize="4"
								:isPreview="false"
								:disabled="isDisabled"
								:isSkelett="isSkelett"
								:otherParams="{
									type: 'video'
								}"
								ref="MaterialDownloadResource"
								:batchDownLoad="!batchDownStatus"
								:singleDownLoad="batchDownStatus"
								:list="materialFileObject.videoList"
								@openPreview="openPreview"
								@singleFileDownload="singleFileDownload"
								@changeResourceListStatus="changeResourceListStatus"
							/>
						</view>
					</swiper-item>
				</swiper>

				<view class="layout-main-content-hint">
					<DistributionHint :type="isHintStatus" />
				</view>
			</view>
		</view>

		<template v-if="isDisabled || downFileLength">
			<CommonMateriaFooter>
				<template slot="footerButton">
					<view class="layout-footer">
						<template v-if="downFileLength && !isDisabled">
							<button class="immediately-button" @click="batchFileDownload">下载至本地相册(共{{ downFileLength }}个)</button>
						</template>

						<template v-else>
							<DownloadProgressBar :list="temporaryStorageList" />
						</template>
					</view>
				</template>
			</CommonMateriaFooter>
		</template>

		<DistributionResourcePreview
			isSelf
			remote
			frequency
			:isPreview="false"
			:list="previewList"
			v-model="isPreviewPopup"
			:index="previewCurrentIndex"
			@changeIndex="changePreviewCurrentIndex"
			:requestOtherParams="{
				preview: false
			}"
		/>
	</view>
</template>

<script>
import { chunk, debounce } from 'lodash';
import { defaultImageUrl } from '@/utils';
import EncapsulationDownLoad from '@/plugIn/downLoad';
import { getMaterailDetail, getBuyMaterialList } from '@/api/material';
import { secondFormatMinute, formatCommissionsModel, hintUploadAndDownload } from '@/utils/common';

import DistributionHint from '@/components/distributionHint';
import CommonMateriaFooter from './components/CommonMateriaFooter';
import CommonMateriaHeader from './components/CommonMateriaHeader';

import DistributionSubTabs from '@/components/distributionSubTabs';
import DistributionMaterial from '@/components/distributionMaterial';

import DistributionNavBar from '@/components/distributionNavBar/indeHome';
import MaterialDownloadResource from './components/MaterialDownloadResource';
import DistributionResourcePreview from '@/components/distributionResourcePreview';

import DownloadProgressBar from './components/DownloadProgressBar';

const bankIcon = Object.freeze(`${defaultImageUrl}help/icon_navbar_back.png`);
const headerIcon = Object.freeze(`${defaultImageUrl}icon/icon_xq_information.png`);

const materialBuyTypeList = Object.freeze([
	{
		type: 'imgPayYuan',
		label: '图片素材'
	},
	{
		type: 'videoPayYuan',
		label: '视频素材'
	},
	{
		type: 'totalPayYuan',
		label: '素材总额'
	},
	{
		type: 'reralPayYuan',
		label: '',
		prefix: '实付款'
	}
]);
const orderTypeList = Object.freeze([
	{
		type: 'orderNo',
		label: '订单编号',
		copy: true
	},
	{
		type: 'uploadTime',
		label: '支付时间'
	},
	{
		type: 'payTypeStr',
		label: '支付类型'
	}
]);

// 顶部导航 rgba
const speed = 100;

export default {
	name: 'MaterialOrderBuy',

	data() {
		this.debounced = debounce((scrollTop) => {
			this.scrollTop = scrollTop;
		}, 16);

		return {
			bankIcon,
			headerIcon,
			orderTypeList,
			materialBuyTypeList,

			scrollTop: 0,
			isPopup: false,
			isSkelett: true,
			tabsType: 'image',
			isHintStatus: '', // nomore

			pageParams: {},
			materailList: [],

			isDisabled: false,
			batchDownStatus: true,

			requestParams: {
				pageIndex: 1,
				pageSize: 30,
				resourceType: 0
			},

			materialResource: {},

			materialFileObject: {
				videoList: [],
				imageList: []
			},

			temporaryStorageList: [],

			previewList: [],
			isPreviewPopup: false,
			previewCurrentIndex: undefined
		};
	},

	created() {
		this.download = new EncapsulationDownLoad({
			that: this
		});

		// #ifdef APP-PLUS
		this.getAppWebview = this.$mp.page.$getAppWebview();
		// #endif
	},

	onLoad(params) {
		const { orderId, approveStatus, cartOrderNo } = params;

		const requestParams = {
			approveStatus,
			productId: orderId,
			orderNo: cartOrderNo
		};

		this.requestParams = {
			...this.requestParams,
			...requestParams
		};

		this.getAllPageData();
	},

	computed: {
		swiperStyle() {
			const {
				$refs: { MaterialDownloadResource },
				materialFileObject: { videoList, imageList }
			} = this;

			const { itemSize, marginLeft, widthHeight } = MaterialDownloadResource || {};

			const videoLength = chunk(videoList, itemSize).length;
			const imageLength = chunk(imageList, itemSize).length;

			const maxLength = Math.max(videoLength, imageLength);

			return {
				height: `${maxLength * (marginLeft + widthHeight)}px`
			};
		},

		navBarRgba() {
			const { scrollTop } = this;

			const opacity = (scrollTop / speed).toFixed(2);

			return `rgba(255, 255, 255, ${opacity})`;
		},

		selectedFileNumber() {
			const {
				materialFileObject: { videoList, imageList }
			} = this;

			const videoLength = videoList.filter((item) => item.isActive).length;
			const imageLength = imageList.filter((item) => item.isActive).length;

			return {
				image: imageLength,
				video: videoLength
			};
		},

		downFileLength() {
			const {
				selectedFileNumber: { image, video }
			} = this;

			return image + video;
		},

		tabsTypeList() {
			const {
				selectedFileNumber: { image, video }
			} = this;

			return [
				{
					type: 'image',
					label: '图片',
					subLabel: image && `(已选${image})`
				},
				{
					type: 'video',
					label: '视频',
					subLabel: video && `(已选${video})`
				}
			];
		},

		isTemporaryStorageList() {
			const { temporaryStorageList } = this;

			const isStatus = !!temporaryStorageList.length;

			// #ifdef APP-PLUS
			this.getAppWebview?.setStyle({
				popGesture: isStatus ? 'none' : 'close'
			});
			// #endif

			return isStatus;
		}
	},

	methods: {
		getAllPageData(pageIndex = this.requestParams.pageIndex) {
			const {
				pageParams,
				requestParams: { pageSize, ...otherParams },
				materialFileObject: { videoList, imageList }
			} = this;

			const params = {
				...otherParams,
				pageSize,
				pageIndex,
				resourceType: 0
			};

			const isPageParams = Object.keys(pageParams).length;

			Promise.all([getBuyMaterialList(params), !isPageParams && getMaterailDetail(otherParams)]).then((res) => {
				const [materialList, detailParams] = res || [];

				const {
					imgNum,
					imgResource,

					videoNum,
					videoResource
				} = materialList?.data || {};

				const isPageIndex = pageIndex === 1;

				const formatImageList = (imgResource || []).map((item) => {
					const { id, url, pixel, coverUrl } = item;

					return {
						id,
						pixel,
						coverUrl,
						type: 'image'
					};
				});

				const formatVideoList = (videoResource || []).map((item) => {
					const { id, pixel, coverUrl, duration, resourceType } = item;

					return {
						id,
						pixel,
						coverUrl,
						type: 'video',
						resourceType,
						duration: secondFormatMinute(duration)
					};
				});

				this.materialFileObject = {
					imageList: isPageIndex ? formatImageList : [...imageList, ...formatImageList],
					videoList: isPageIndex ? formatVideoList : [...videoList, ...formatVideoList]
				};

				this.isHintStatus = formatImageList.length < pageSize && formatVideoList.length < pageSize ? 'nomore' : '';

				if (isPageParams) {
					return;
				}

				const {
					faceImg,
					commission,
					productName,

					originPrice,
					originPriceYuan,

					salePrice,
					salePriceYuan,

					...otherParams
				} = detailParams?.data || {};

				this.pageParams = otherParams;

				this.materailList = [
					{
						faceImg,
						salePrice,
						originPrice,
						productTitle: productName,
						commissionsList: formatCommissionsModel(commission)
					}
				];

				this.isSkelett = false;
			});
		},

		async clickBack() {
			const { isTemporaryStorageList } = this;

			if (!isTemporaryStorageList) {
				uni.navigateBack();
				return;
			}

			const res = await hintUploadAndDownload(false);

			if (!res.confirm) {
				uni.navigateBack();
				this.upload.allAbortUpload();
				return;
			}
		},

		changeTypeTabs(params) {
			console.log(params, 'params');
		},

		changeScrollView(params) {
			console.log(params, 'params');
		},

		changeTabsType(params) {
			this.tabsType = params?.detail?.currentItemId;
		},

		copyOrderNo({ type }) {
			const { pageParams } = this;

			uni.setClipboardData({
				data: pageParams[type]
			});
		},

		changeResourceListStatus(params) {
			const { type, currentIndex } = params;
			const {
				materialFileObject: { videoList, imageList }
			} = this;

			const target = (type === 'image' ? imageList : videoList)[currentIndex];

			this.$set(target, 'isActive', !target.isActive);
		},

		changeBatchDownloadStatus() {
			const { isDisabled } = this;

			if (isDisabled) {
				return;
			}

			this.batchDownStatus = !this.batchDownStatus;
			this.cancelALLSelectedFileStatus();
		},

		cancelALLSelectedFileStatus() {
			const {
				materialFileObject: { videoList, imageList }
			} = this;

			imageList.forEach((item) => item.isActive && this.$set(item, 'isActive', false));
			videoList.forEach((item) => item.isActive && this.$set(item, 'isActive', false));
		},

		batchFileDownload() {
			const {
				materialFileObject: { videoList, imageList }
			} = this;

			this.isDisabled = true;

			const formatList = [imageList.filter((item) => item.isActive), videoList.filter((item) => item.isActive)]
				.flat(2)
				.map((item) => ({ ...item }));

			this.temporaryStorageList = formatList;
			this.download.startDownloadFile();
		},

		singleFileDownload(params = {}) {
			const formatParams = params?.$orig ?? params;

			this.isDisabled = true;

			if (!Object.keys(formatParams).length) {
				return;
			}

			this.temporaryStorageList = [
				{
					...formatParams
				}
			];
			this.download.startDownloadFile();
		},

		allFileDownCallBack() {
			const { temporaryStorageList } = this;

			const successLength = temporaryStorageList.filter((item) => item.status === 'success').length;

			uni.showToast({
				mask: true,
				icon: 'none',
				title: `已成功下载${successLength}个资源。`
			});

			this.isDisabled = false;
			this.temporaryStorageList = [];

			this.cancelALLSelectedFileStatus();
		},

		openPreview({ previewList, previewCurrentIndex }) {
			this.previewList = previewList;
			this.previewCurrentIndex = previewCurrentIndex;

			this.isPreviewPopup = true;
		},

		changePreviewCurrentIndex(index) {
			this.previewCurrentIndex = index;
		}
	},

	// #ifdef APP-PLUS
	onBackPress(params) {
		const { from } = params;

		if (from === 'navigateBack') {
			return;
		}

		this.clickBack();
		return true;
	},
	// #endif

	onReachBottom() {
		const {
			isSkelett,
			isHintStatus,
			requestParams: { pageIndex }
		} = this;

		if (isHintStatus || isSkelett) {
			return;
		}

		this.isHintStatus = 'loading';
		this.getAllPageData(pageIndex + 1);
	},

	onPageScroll({ scrollTop }) {
		this.debounced?.(scrollTop);
	},

	onUnload() {
		const { temporaryStorageList } = this;

		temporaryStorageList.length && this.download.allAbortUpload();
	},

	components: {
		DistributionHint,
		DistributionNavBar,
		DistributionSubTabs,

		CommonMateriaHeader,
		DistributionMaterial,
		CommonMateriaFooter,
		DownloadProgressBar,
		MaterialDownloadResource,
		DistributionResourcePreview
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	background: #fff;
	min-height: 100vh;
	overflow-x: hidden;
	@include Db_iosBottomDistance();

	/deep/ .product-price-right {
		view {
			&:first-child {
				color: #333 !important;

				text {
					color: #333 !important;
				}
			}
		}
	}

	&-main {
		position: relative;
		margin-top: 20rpx;
		padding-top: 8rpx;

		background: #fff;
		border-radius: 24rpx 24rpx 0 0;

		&-tabs {
			display: flex;
			align-items: center;
			justify-content: space-between;

			view {
				flex: 1;
			}

			&-right {
				display: flex;
				align-items: center;
				flex-direction: row-reverse;

				button {
					padding: 0;
					color: #ff6b11;
					font-size: 24rpx;

					width: 144rpx;
					height: 48rpx;
					line-height: 44rpx;
					background: #fff;
					margin: 0 20rpx 0 0;
					border-radius: 24rpx;
					border: 2rpx solid #ff6b11;

					&::after {
						border: none;
					}
				}
			}
		}

		&-content {
			margin-top: 4rpx;

			.scroll-view {
				white-space: nowrap;
			}

			&-item {
				width: 100%;
				display: inline-block;
			}

			&-hint {
				margin-top: 20rpx;
			}
		}
	}

	&-nav {
		margin: 0 -20rpx;

		image {
			width: 40rpx;
			height: 40rpx;
		}
	}

	&-header {
		position: relative;
		padding: 20rpx 20rpx 0;

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			height: 204rpx;
			background: linear-gradient(180deg, #fff7f2 0%, #f6f6f6 100%);
		}

		&-main {
			margin-top: -18rpx;
			padding-bottom: 20rpx;

			&-type {
				margin-top: 24rpx;
				padding: 0 20rpx 0 48rpx;

				&-item {
					display: flex;
					align-items: center;
					justify-content: space-between;

					font-size: 26rpx;
					margin-top: 24rpx;

					&-left {
						color: #666;
					}

					&-right {
						color: #333;

						text {
							color: #1f1f1f;
							font-weight: bold;
							margin-left: 8rpx;

							&.realPayment {
								font-size: 36rpx;

								@include Db_moneyStyle();
							}
						}
					}

					&:first-child {
						margin-top: 0;
					}
				}
			}

			&-order {
				margin: 0 20rpx;
				margin-top: 22rpx;
				background: #f6f6f6;
				border-radius: 16rpx;
				padding-left: 28rpx;
				overflow: hidden;

				&-item {
					display: flex;
					align-items: center;

					font-size: 26rpx;
					margin-top: 20rpx;

					&-left {
						width: 150rpx;
						color: #666;
					}

					&-right {
						flex: 1;

						color: #1f1f1f;
						font-weight: bold;

						display: flex;
						align-items: center;

						button {
							margin: 0 0 0 24rpx;
							padding: 0;
							height: 36rpx;
							width: 64rpx;
							line-height: 32rpx;
							font-size: 20rpx;
							font-weight: 400;
							border-radius: 12rpx;
							background: #fff;
							border: 2rpx solid #cccccc;

							&::after {
								border: none;
							}
						}
					}

					&:last-child {
						margin-bottom: 20rpx;
					}
				}
			}
		}
	}

	&-footer {
		display: flex;
		padding: 0 28rpx;

		button {
			flex: 1;
			@include Db_commonButton(80rpx, 24rpx);

			&.immediately-button {
				background: #ff6b11;

				&:active {
					background: rgba(255, 107, 17, 0.7);
				}
			}
		}
	}

	// 骨架图
	&.skelett {
		.layout-header-main {
			&-type-item {
				view {
					min-width: 220rpx;
					border-radius: 12rpx;
					background: $skelettBgColor;

					text {
						visibility: hidden;
					}

					&:last-child {
						min-width: 280rpx;
					}
				}
			}

			&-order {
				background: $skelettBgColor;

				view {
					visibility: hidden;
				}
			}
		}
	}

	/deep/ .commonMateriaHeader-main {
		padding: 0 !important;
	}

	&.footer {
		@include Db_iosBottomDistance(140rpx);
	}
}
</style>
